import random
from qcloudsms_py import SmsSingleSender
from utilss.loggings import logger

from . import settings

"""
@author RansySun
@create 2019-12-02-20:51
"""

sender = SmsSingleSender(settings.APP_ID, settings.APP_KEY)


def send_sms(mobile, code, exp):
    """
    获取验证码
    需要手机号、验证码、过期时间(min)
    :param mobile: 手机号
    :param code: 验证码
    :param exp: 过期时间
    """
    try:
        response = sender.send_with_param(
            86,
            mobile,
            settings.TEMPLATE_ID,
            params=[code, exp],
            sign=settings.SMS_SIGN,
            extend="",
            ext=""
        )
        if response.get("result") == 0 and response:
            return True
        # 失败的状态码
        msg = response.get("result")
    except Exception as msg:  # 失败的信息
        pass
    logger.error(f"短信发送失败:{msg}")


def get_code():
    """
    获取验证码
    :return:
    """
    code = ""
    for i in range(4):
        code += str(random.randint(0, 9))
    return code
